﻿using AnlianCommon.Common.Domains.ProductionManagement;
using AnlianCommon.Common.DTO;
using AnlianCommon.Common.Infrastructure.IRepository;
using AnlianCommon.Enum;
using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace SheepCommon.API.SheepCommands.Breedingsettinges
{
    public class BreedingsettingCreateHandler : IRequestHandler<BreedingsettingCreateCommand, Result>
    {
        private readonly IBaseRepository<Breedingsetting> _breedingsettingRepository;
        private readonly IBaseRepository <SheepArchives> _sheepArchiveRepository;
        private readonly IMapper _mapper;

        public BreedingsettingCreateHandler(IBaseRepository<Breedingsetting> breedingsettingRepository, IBaseRepository<SheepArchives> sheepArchiveRepository, IMapper mapper)
        {
            _breedingsettingRepository = breedingsettingRepository;
            _sheepArchiveRepository = sheepArchiveRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(BreedingsettingCreateCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                Breedingsetting breedingsetting = _mapper.Map<Breedingsetting>(request);
                breedingsetting.BreedingsettingTime = DateTime.Now;
                breedingsetting.CreatedOwnerId = "张三";
                breedingsetting.CreatedTime = DateTime.Now;
                var res = await _breedingsettingRepository.Add(breedingsetting);
                if (res > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "添加成功";
                    //查询档案表条件耳号
                    var cc =await(await _sheepArchiveRepository.GetAll()).Where(c=>c.RecordAuricle==request.RecordAuricle).FirstOrDefaultAsync();
                    if (cc != null)
                    {
                        cc.ReproductiveState = 7;//1表示后备空怀,2返情空怀,3未孕空怀,4流产空怀,5空胎空怀,6断奶空怀,7妊检,8哺乳
                        var dd = await _sheepArchiveRepository.Update(cc);
                    }
                }
                else
                {
                    result.Code = (int)CommonErrorCode.Added;
                    result.Msg = "添加失败";
                }
            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
    }
}
